<template>
  <jke-modal
    :visible.sync="jkeForm.visible"
    :width="1200"
    :title="jkeForm.title"
    :fullscreen.sync="jkeForm.fullscreen"
    :switchFullscreen="jkeForm.switchFullscreen"
  >
    <!--  -->
    <crumbs
      @goBack="goBack"
      :superiorMenu="['基础管理', '设备保养', '保养方案']"
      marginBottom="10px"
      :currentMenu="jkeForm.title"
    ></crumbs>
    <div class="form-body">
      <a-card title="基本信息" :bordered="false">
        <a-form :form="form" @submit="handleSubmit" layout="vertical">
          <a-form-item label="方案编号" required>
            <a-input
              v-decorator="[
                'programCode',
                {
                  rules: [
                    {
                      required: true,
                      message: '请输入方案编号',
                    },
                    {
                      message: '该值不可用，系统中已存在！',
                      validator: (rule, value, callback) =>
                        validateDuplicateValue(
                          'mess_device_maintain_program',
                          'program_code',
                          value,
                          queryId,
                          callback
                        ),
                    },
                  ],
                },
              ]"
              placeholder="请输入"
              :maxLength="16"
              :disabled="isEdit"
            />
            <span class="btn-text code-btn" @click="genEntityCode" v-if="!isEdit">自动生成</span>
          </a-form-item>
          <a-form-item label="方案名称">
            <a-input
              :maxLength="30"
              v-decorator="['programName', { rules: [{ required: true, message: '请输入方案名称' }] }]"
              placeholder="请输入"
            />
          </a-form-item>
          <a-form-item label="状态">
            <a-select
              default-value="enable"
              style="width: 100%"
              placeholder="请选择"
              allowClear
              v-decorator="['programStatus', { rules: [{ required: true, message: '请选择状态' }] }]"
            >
              <a-select-option v-for="o in statusList" :key="o.value" :value="o.value">
                {{ o.text }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-form>
      </a-card>
      <a-card title="设备信息" :bordered="false" style="margin-top: 12px">
        <a-form :form="form" @submit="handleSubmit" layout="vertical">
          <a-form-item label="设备类别">
            <a-select
              style="width: 100%"
              placeholder="请选择"
              v-decorator="['deviceCategory', { rules: [{ required: true, message: '请选择设备类别' }] }]"
              @change="chaged"
              allowClear
              :disabled="isEdit"
            >
              <a-select-option v-for="o in typeList" :key="o.value" :value="o.value">
                {{ o.text }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="保养设备">
            <a-select
              mode="multiple"
              style="width: 100%"
              :filterOption="filterOption"
              placeholder="请先选择设备类别"
              allowClear
              @focus="focusCare"
              v-decorator="['deviceId', { rules: [{ required: true, message: '请选择保养设备' }] }]"
            >
              <a-select-option v-for="o in careList" :key="o.value" :value="o.value">
                {{ o.text }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <div class="ant-form-item"></div>
        </a-form>
      </a-card>
      <a-card title="时间方案" :bordered="false" style="margin-top: 12px">
        <a-form :form="form" @submit="handleSubmit" layout="vertical">
          <a-form-item label="方案开始日期">
            <a-date-picker
              v-decorator="['startDate', { rules: [{ required: true, message: '请选择方案开始日期' }] }]"
              style="width: 100%"
              placeholder="请选择"
              allowClear
              @change="(e) => (startValue = e)"
              :disabled-date="disabledStartDate"
              :disabled="isEdit"
            />
          </a-form-item>
          <a-form-item label="方案结束日期">
            <a-date-picker
              v-decorator="['endDate']"
              style="width: 100%"
              placeholder="请选择"
              allowClear
              @change="(e) => (endValue = e)"
              :disabled-date="disabledEndDate"
              :disabled="isEdit"
            />
          </a-form-item>
          <div class="ant-form-item"></div>
        </a-form>
        <a-form :form="form" @submit="handleSubmit" layout="vertical">
          <a-form-item label="周期数">
            <a-input
              @input="(e) => inputNums(e)"
              v-decorator="['periodNum', { rules: [{ required: true, message: '请输入周期数' }] }]"
              placeholder="请输入"
              :disabled="isEdit"
            />
          </a-form-item>
          <a-form-item label="周期单位">
            <a-select
              default-value="1"
              style="width: 100%"
              allowClear
              placeholder="请选择"
              v-decorator="['periodUnit', { rules: [{ required: true, message: '请选择周期单位' }] }]"
              :disabled="isEdit"
            >
              <a-select-option v-for="o in unitList" :key="o.value" :value="o.value">
                {{ o.text }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <div class="ant-form-item"></div>
        </a-form>
      </a-card>
      <a-card title="保养项目" :bordered="false" style="margin-top: 12px">
        <j-editable-table
          ref="goodsTable"
          :loading="goodsTable.loading"
          :columns="goodsTable.columns"
          :dataSource="goodsTable.dataSource"
          :maxHeight="300"
          :rowNumber="true"
          :actionButton="true"
        >
          <template v-slot:action="props">
            <a-popconfirm title="是否删除?" ok-text="是" cancel-text="否" @confirm="handleDeleteCare(props)">
              <span class="del-text">删除</span>
            </a-popconfirm>
          </template>
          <template v-slot:itemId="props">
            <a-input
              placeholder="请选择"
              :read-only="true"
              @click="showSelect(props)"
              :value="goodsNameText(props)"
              :class="goodsNameText(props) ? 'has-value' : ''"
            >
              <a-icon slot="suffix" type="down" style="color: #cdcdcd; font-size: 12px" class="down-icon" />
              <a-icon
                slot="suffix"
                type="close-circle"
                theme="filled"
                class="close-icon"
                @click="getSelectValue(false, '', [], props.rowId)"
              />
            </a-input>
          </template>
        </j-editable-table>
      </a-card>
      <a-card title="其他" :bordered="false" style="margin-top: 12px">
        <a-form :form="form" @submit="handleSubmit" layout="vertical">
          <a-form-item label="备注" style="flex: 1">
            <a-textarea
              placeholder="请输入"
              :maxLength="500"
              :auto-size="{ minRows: 2, maxRows: 6 }"
              v-decorator="['remark']"
            />
          </a-form-item>
        </a-form>
        <a-form layout="vertical">
          <a-form-item label="附件" style="flex: 1">
            <file-upload :ids="attachment" @getFileList="getFileList"></file-upload>
            <p style="line-height: 30px;color:#8d8d8d;">最多上传5个文件，大小不可超过20M</p>
          </a-form-item>
        </a-form>
      </a-card>
    </div>

    <div class="footer-submit form-footer">
      <a-button type="primary" :loading="loadingSubmit" @click="handleSubmit"> 提交 </a-button>
    </div>
    <tableSelect
      ref="tableSelect"
      @getSelectValue="(id, text, item) => getSelectValue(id, text, item)"
      :key="selectIndex"
    >
      <!-- <div slot="head">我是插槽，写入搜索重置等功能</div> -->
      <div slot="head">
        <div class="uni-card" style="background: #fff">
          <a-form-model ref="ruleForm" layout="inline" :model="filterForm">
            <a-form-model-item label="项目编号">
              <a-input v-model="filterForm.projectCode" placeholder="请输入" />
            </a-form-model-item>
            <a-form-model-item label="项目名称">
              <a-input v-model="filterForm.projectName" placeholder="请输入" />
            </a-form-model-item>
            <a-form-model-item>
              <a-button @click="searchGoods()" type="primary"> 搜索 </a-button>
              <a-button style="margin-left: 10px" @click="searchResetGoods">重置</a-button>
            </a-form-model-item>
          </a-form-model>
        </div>
      </div>
    </tableSelect>
  </jke-modal>
</template>
<script>
import crumbs from '@/components/crumbs.vue'
import FileUpload from '@/components/fileActions/FileUpload.vue'
import { API } from '@/api/requestFzs'
import moment from 'moment'
import { integerNum, validateDuplicateValue } from '@/utils/util'
import JEditableTable from '@/components/jeecg/JEditableTable.vue'
import { FormTypes } from '@/utils/JEditableTableUtil'
import tableSelect from '@/components/tableSelect'
import { ajaxGetDictItems } from '@/api/api'
export default {
  data() {
    return {
      jkeForm: {
        title: '新建保养方案',
        visible: false,
        fullscreen: true,
        switchFullscreen: true,
      },
      validateDuplicateValue,
      form: this.$form.createForm(this, { name: 'coordinated' }),
      attachment: '',
      submitApi: API.messDeviceMaintainProgramAdd,
      isEdit: false,
      queryId: '',
      loadingSubmit: false,
      // 状态下拉
      statusList: [
        { text: '启用', value: 'enable' },
        { text: '禁用', value: 'disable' },
      ],
      // 设备类别下拉
      typeList: [],
      // 保养设备下拉
      careList: [],
      // 周期单位下拉
      unitList: [],
      startValue: null,
      endValue: null,
      goodsTable: {
        loading: false,
        dataSource: [{}],
        columns: [
          {
            title: '保养项',
            width: '40%',
            key: 'itemId',
            type: FormTypes.slot,
            placeholder: '请输入${title}',
            slotName: 'itemId',
            isrequired: true,
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }],
          },
          { title: '保养项编号', key: 'projectCode', type: FormTypes.hidden },
          { title: '保养项名称', key: 'projectName', type: FormTypes.hidden },
          { title: '方案id', key: 'programId', type: FormTypes.hidden },
          { title: '序号', key: 'serialNo', type: FormTypes.hidden },
          {
            title: '保养标准',
            width: '40%',
            key: 'maintainStandard',
            type: FormTypes.input,
            placeholder: '请选择保养项',
            slotName: 'basicUnit',
            disabled: true,
            defaultValue: '',
          },
          {
            title: '操作',
            width: '5%',
            key: 'action',
            type: FormTypes.slot,
            placeholder: '选择${title}',
            slotName: 'action',
            defaultValue: '',
          },
        ],
      },
      caresProps: {},
      selectColumns: [
        {
          title: '项目编号',
          // align: 'center',
          dataIndex: 'projectCode',
        },
        {
          title: '项目名称',
          // align: 'center',
          dataIndex: 'projectName',
        },
        {
          title: '保养标准',
          // align: 'center',
          dataIndex: 'maintainStandard',
        },
      ],
      selectIndex: 0,
      filterForm: {},
    }
  },
  components: {
    FileUpload,
    crumbs,
    tableSelect,
    JEditableTable,
  },
  methods: {
    // 保养设备下拉筛选
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    // 设备类别变化后清空保养设备
    chaged(e) {
      this.careList = []
      this.$nextTick(() => {
        this.form.setFieldsValue({
          deviceId: undefined,
        })
      })
      if (e) {
        API.pageQueryDeviceEntity({ deviceCategory: e }).then((res) => {
          if (res.result.records) {
            res.result.records.forEach((item) => {
              this.careList.push({
                text: `${item.deviceCode}-${item.deviceName}`,
                value: item.id,
              })
            })
          }
        })
      }
    },
    // 选择保养设备前先判断是否已选设备类别
    focusCare() {
      let care = this.form.getFieldsValue(['deviceCategory'])
      if (!care.deviceCategory) {
        this.$antdMessage.warning('请先选择设备类别')
      }
    },
    // 限制开始日期
    disabledStartDate(startValue) {
      const endValue = this.endValue
      if (!startValue || !endValue) {
        if (moment(startValue).isBefore(moment().add(-1, 'days'))) {
          return true
        }
        return false
      } else {
        if (moment(startValue).isBefore(moment().add(-1, 'days'))) {
          return true
        } else {
          return moment(startValue).isAfter(moment(endValue))
          // return startValue.valueOf() > endValue.valueOf()
        }
      }
    },
    // 限制结束日期
    disabledEndDate(endValue) {
      const startValue = this.startValue
      if (!endValue || !startValue) {
        if (moment(endValue).isBefore(moment().add(-1, 'days'))) {
          return true
        }
        return false
      } else {
        if (moment(startValue).isBefore(moment().add(-1, 'days'))) {
          return true
        } else {
          return moment(startValue).isAfter(moment(endValue))
          // return startValue.valueOf() > endValue.valueOf()
        }
      }
    },
    // 点击保养项下拉框，弹出选择组件
    showSelect(p) {
      this.caresProps = p
      var tableValue = this.$refs.goodsTable.getValuesSync({ validate: false, rowIds: [p.rowId] }).values[0]
      let par = {
        list: '/mess/messDeviceMaintainItem/list',
        visible: true, //弹窗开启
        title: '保养项目', //标题名称
        multi: false, //是否多选
        columns: this.selectColumns, //表格配置
        value: tableValue.itemId || '', //需要回显的数据，如：id:'12323213,321312312,321312312'
        valueKey: 'id', //需要拿到数据的key，如：id，userId等
        text: tableValue.projectCode || '', //回显的中文，如：'张三'
        textKey: 'projectCode', //回显的中文key
      }
      this.$refs.tableSelect.getInit(par)
    },
    // 选择保养回调
    getSelectValue(id, text, item, rowId) {
      this.selectIndex += 1 //重置组件去除表格默认勾选数据，让自己赋值的数据回显（重要！！！）
      if (!id) {
        this.$refs.goodsTable.setValues([
          {
            rowKey: rowId, // 行的id
            values: {
              // 在这里 values 中的 goodsId 是你 columns 中配置的 key
              itemId: '',
              projectCode: '',
              projectName: '',
              maintainStandard: '',
            },
          },
        ])
        return
      }
      var tableValue = this.$refs.goodsTable.getValuesSync({ validate: false }).values
      tableValue.forEach((v) => {
        if (v.itemId == id && this.caresProps.rowId != v.id) {
          this.$refs.goodsTable.removeRows(this.caresProps.rowId)
          this.$antdMessage.warning('该项目已存在，请重新选择')
          return
        }
      })
      this.$refs.goodsTable.setValues([
        {
          rowKey: this.caresProps.rowId, // 行的id
          values: {
            // 在这里 values 中的 goodsId 是你 columns 中配置的 key
            itemId: id,
            projectCode: text,
            projectName: item[0].projectName || '',
            maintainStandard: item[0].maintainStandard || '',
          },
        },
      ])
      this.$refs.goodsTable.getValuesSync({ validate: true })
    },
    // 保养项选择框回显值
    goodsNameText(p) {
      var item = this.$refs.goodsTable.getValuesSync({ validate: false, rowIds: [p.rowId] }).values[0]
      console.log('itemssssss:', item)
      return item.projectCode ? `${item.projectCode}-${item.projectName}` : ''
    },
    // 重置
    searchResetGoods() {
      this.filterForm = {}
      this.$refs.tableSelect.searchReset()
    },
    // 筛选
    searchGoods() {
      this.$refs.tableSelect.searchQuery(this.filterForm)
    },
    // 删除列表项
    handleDeleteCare(p) {
      this.$refs.goodsTable.removeRows(p.rowId)
    },
    inputNums(v) {
      console.log(v)
      this.$nextTick(() => {
        this.form.setFieldsValue({
          periodNum: integerNum(v.target.value),
        })
      })
    },
    /* 面包屑返回 */
    goBack() {
      this.jkeForm.visible = false
    },
    /* 获取编辑详情 */
    initForm(id) {
      Object.assign(this.$data, this.$options.data.call(this));
      this.jkeForm.visible = true
      this.queryId = id
      if (id) {
        this.jkeForm.title = '编辑保养方案'
        this.submitApi = API.messDeviceMaintainProgramEdit
        this.isEdit = true
        API.messDeviceMaintainProgramQueryById({ id }).then((res) => {
          if (res.code == 200) {
            let formdata = res.result
            let deArr = []
            formdata.deviceList.forEach((d) => {
              deArr.push(d.deviceId)
            })
            formdata.deviceId = deArr
            this.form.setFieldsValue(formdata)
            API.pageQueryDeviceEntity({ deviceCategory: formdata.deviceCategory }).then((res) => {
              if (res.result.records) {
                res.result.records.forEach((item) => {
                  this.careList.push({
                    text: `${item.deviceName}-${item.deviceCode}`,
                    value: item.id,
                  })
                })
              }
            })
            this.attachment = formdata.attachment
            this.goodsTable.dataSource = formdata.itemList
          }
        })
      } else {
        this.jkeForm.title = '新建保养方案'
        this.$nextTick(() => {
          this.form.setFieldsValue({
            programStatus: 'enable',
            startDate: moment(),
          })
        })
      }
      ajaxGetDictItems('mess_device_category', null).then((res) => {
        if (res.success) {
          this.typeList = res.result
        }
      })
      ajaxGetDictItems('program_period_unit', null).then((res) => {
        if (res.success) {
          this.unitList = res.result
        }
      })
    },
    /* 自动生成 */
    genEntityCode() {
      API.genEntityCode({ entityCode: 'MESS_DEVICE_MAINTAIN_PROGRAM' }).then((res) => {
        if (res.code == 200) {
          this.form.setFieldsValue({
            programCode: res.result,
          })
        } else {
          this.$antdMessage.error(res.message)
        }
      })
    },
    /* 获取附件 */
    getFileList(v) {
      this.attachment = v
      console.log('上传的附件id：', v)
    },
    handleSubmit() {
      let tableValue = this.$refs.goodsTable.getValuesSync({ validate: true })
      this.form.validateFields((err, values) => {
        if (!err && tableValue.error === 0) {
          if (tableValue.values.length == 0) {
            this.$antdMessage.warning('请添加保养项目')
            return
          }
          let parameters = { ...values, attachment: this.attachment }
          parameters.startDate = parameters.startDate ? moment(parameters.startDate).format('YYYY-MM-DD') : ''
          parameters.endDate = parameters.endDate ? moment(parameters.endDate).format('YYYY-MM-DD') : ''
          parameters.itemList = tableValue.values
          parameters.deviceId = parameters.deviceId.join(',')
          if (this.isEdit) {
            parameters.id = this.queryId
          }
          parameters.itemList.forEach((p, j) => {
            p.serialNo = j
            if (this.isEdit) {
              p.programId = this.queryId
            }
          })
          this.loadingSubmit = true
          this.submitApi(parameters).then((res) => {
            this.loadingSubmit = false
            if (res.code == 200) {
              let subMsg = this.isEdit ? '保养方案编辑成功！' : '保养方案创建成功！'
              this.$antdMessage.success(subMsg)
              this.$emit('refresh')
              this.goBack()
            }
          })
        } else {
          console.error(err, tableValue.error)
        }
      })
    },
  },
}
</script>
<style scoped lang="less">
@import '~@/assets/less/public.less';
/deep/.ant-form-vertical {
  display: flex;
  justify-content: space-between;
  .ant-form-item {
    width: 30%;
  }
}
.form-body {
  height: calc(100vh - 120px);
  overflow-y: scroll;
}
.code-btn {
  position: absolute;
  right: 0;
  top: -34.5px;
}
</style>


